<template>
  <div>
    <baseTable :page.sync="pageQuery" :cols="cols" :tableData="userList">
      <template v-slot:header>
        <div class="top">
          <div>
            <el-select
              v-model="pageQuery.roleId"
              placeholder="请选择用户角色"
              class="w-48 mr-4"
              clearable
            >
              <el-option
                v-for="item in roleOptions"
                :key="item.pkid"
                :label="item.roleName"
                :value="item.pkid"
              >
              </el-option>
            </el-select>
            <el-select
              v-model="pageQuery.userState"
              placeholder="请选择用户状态"
              class="w-48 mr-4"
              clearable
            >
              <el-option
                v-for="item in userStateOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              >
              </el-option>
            </el-select>
            <!-- <el-input
              placeholder="请输入用户名、真实姓名"
              v-model="pageQuery.userName"
              style="width:280px"
              class="mr-4"
            >
              <template #append>
                <el-button> 搜索 </el-button>
              </template>
            </el-input> -->
            <el-input
              placeholder="请输入用户名、真实姓名"
              v-model="pageQuery.userName"
              suffix-icon="el-icon-search"
              style="width: 250px"
            >
            </el-input>
          </div>
          <el-button
            type="primary"
            icon="el-icon-plus"
            @click="addUserDialogVisible = true"
            >新增用户</el-button
          >
        </div>
      </template>
      <template v-slot:operation>
        <el-table-column label="操作" align="center">
          <template v-slot="scope">
            <el-button type="text" @click="handleEdit(scope.row)"
              >编辑</el-button
            >
            <el-button type="text" @click="removeUser(scope.row)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </template>
    </baseTable>
    <el-dialog
      title="新增用户"
      :visible.sync="addUserDialogVisible"
      width="30%"
      @closed="handleAddUserDialogClosed"
      :close-on-click-modal="false"
    >
      <el-form
        ref="addUserFormRef"
        :model="addUserForm"
        :rules="addUserFormRules"
        label-width="80px"
      >
        <el-form-item label="用户名" prop="loginName">
          <el-input v-model="addUserForm.loginName"></el-input>
        </el-form-item>
        <el-form-item label="真实姓名" prop="userName">
          <el-input v-model="addUserForm.userName"></el-input>
        </el-form-item>
        <el-form-item label="登陆密码" prop="loginPassword">
          <el-input
            v-model="addUserForm.loginPassword"
            show-password
          ></el-input>
        </el-form-item>
        <el-form-item label="联系电话" prop="userPhone">
          <el-input v-model="addUserForm.userPhone"></el-input>
        </el-form-item>
        <el-form-item label="电子邮箱" prop="userEmail">
          <el-input v-model="addUserForm.userEmail"></el-input>
        </el-form-item>
        <el-form-item label="用户角色" prop="userLevel">
          <el-radio v-model="addUserForm.userLevel" :label="1"
            >普通用户</el-radio
          >
          <el-radio v-model="addUserForm.userLevel" :label="2"
            >部门管理员</el-radio
          >
          <el-radio v-model="addUserForm.userLevel" :label="3"
            >超级管理员</el-radio
          >
        </el-form-item>
        <el-form-item label="所属部门" prop="deptId">
          <el-cascader
            v-model="addUserForm.deptId"
            :options="deptOptions"
            :props="{ checkStrictly: true, emitPath: false }"
            clearable
          ></el-cascader>
        </el-form-item>
        <el-form-item label="用户状态" prop="userState">
          <el-switch
            v-model="addUserForm.userState"
            :active-text="addUserForm.userState ? '启用' : '禁用'"
          >
          </el-switch>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input
            v-model="addUserForm.remark"
            maxlength="50"
            show-word-limit
          ></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="addUserDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="confirmAddUser">确 定</el-button>
        </span>
      </template>
    </el-dialog>
    <el-dialog
      title="编辑用户信息"
      :visible.sync="editUserDialogVisible"
      width="30%"
      @closed="handleEditUserDialogClosed"
      :close-on-click-modal="false"
    >
      <el-form
        ref="editUserFormRef"
        :model="editUserForm"
        :rules="editUserFormRules"
        label-width="80px"
      >
        <el-form-item label="用户名" prop="loginName">
          <el-input
            v-model="editUserForm.loginName"
            readonly
            disabled
          ></el-input>
        </el-form-item>
        <el-form-item label="真实姓名" prop="userName">
          <el-input v-model="editUserForm.userName"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="" v-show="!editPasswordShow">
          <el-input value="************" disabled>
            <el-button
              slot="append"
              icon="el-icon-edit-outline"
              @click="editPasswordShow = true"
            ></el-button>
          </el-input>
        </el-form-item>
        <el-form-item
          label="修改密码"
          prop="loginPassword"
          v-show="editPasswordShow"
        >
          <el-input
            v-model="editUserForm.loginPassword"
            show-password
          ></el-input>
        </el-form-item>
        <el-form-item
          label="确认密码"
          prop="confirmLoginPassword"
          v-show="editPasswordShow"
        >
          <el-input
            v-model="editUserForm.confirmLoginPassword"
            show-password
          ></el-input>
        </el-form-item>
        <el-form-item label="联系电话" prop="userPhone">
          <el-input v-model="editUserForm.userPhone"></el-input>
        </el-form-item>
        <el-form-item label="电子邮箱" prop="userEmail">
          <el-input v-model="editUserForm.userEmail"></el-input>
        </el-form-item>
        <el-form-item label="用户角色" prop="userLevel">
          <el-radio
            v-model="editUserForm.userLevel"
            :label="1"
            readonly
            disabled
            >普通用户</el-radio
          >
          <el-radio
            v-model="editUserForm.userLevel"
            :label="2"
            readonly
            disabled
            >部门管理员</el-radio
          >
          <el-radio
            v-model="editUserForm.userLevel"
            :label="3"
            readonly
            disabled
            >超级管理员</el-radio
          >
        </el-form-item>
        <el-form-item label="所属部门" prop="deptId">
          <el-cascader
            v-model="editUserForm.deptId"
            :options="deptOptions"
            :props="{ checkStrictly: true, emitPath: false }"
            clearable
          ></el-cascader>
        </el-form-item>
        <el-form-item label="用户状态" prop="userState">
          <el-switch
            v-model="editUserForm.userState"
            :active-text="editUserForm.userState ? '启用' : '禁用'"
          >
          </el-switch>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input
            v-model="editUserForm.remark"
            maxlength="50"
            show-word-limit
          ></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="editUserDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="confirmEditUser">确 定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import baseTable from './compoents/baseTable.vue'
import {
  getUserList,
  deleteUser,
  addUser,
  updateUser,
  getRoleList,
} from '@/api/user-manager'
import { getDepartmentTree } from '@/api/department'
export default {
  name: 'user',
  components: {
    baseTable,
  },
  data() {
    return {
      addUserDialogVisible: false,
      pageQuery: {
        userName: '',
        roleId: '',
        userState: '',
        pageIndex: 1,
        pageSize: 20,
        total: 0,
      },
      cols: [
        {
          prop: 'loginName',
          label: '用户名',
        },
        {
          prop: 'userName',
          label: '真实姓名',
        },
        {
          prop: 'roleName',
          label: '用户角色',
        },
        {
          prop: 'deptName',
          label: '所属部门',
        },
        {
          prop: 'userStateCn',
          label: '用户状态',
        },
        {
          prop: 'userPhone',
          label: '联系电话',
        },
        {
          prop: 'userEmail',
          label: '电子邮箱',
        },
        {
          prop: 'createTime',
          label: '创建时间',
        },
        {
          prop: 'updateTime',
          label: '修改时间',
        },
        {
          prop: 'lastLoginTime',
          label: '最后登陆时间',
        },
        {
          prop: 'loginTimes',
          label: '登陆次数',
        },
        {
          prop: 'remark',
          label: '备注',
        },
      ],
      userList: [],
      addUserForm: {
        loginName: '',
        userName: '',
        loginPassword: '',
        // confirmPassword: "",
        userPhone: '',
        userEmail: '',
        userLevel: 1,
        userState: true,
        remark: '',
        deptId: '',
      },
      addUserFormRules: {
        loginName: [
          {
            required: true,
            message: '请输入用户名',
            trigger: ['blur', 'change'],
          },
        ],
        userName: [
          {
            required: true,
            message: '请输入真实姓名',
            trigger: ['blur', 'change'],
          },
        ],
        loginPassword: [
          {
            required: true,
            message: '请输入登陆密码',
            trigger: ['blur', 'change'],
          },
        ],
        // userPhone: [
        //   {
        //     required: true,
        //     message: '请输入联系电话',
        //     trigger: ['blur', 'change'],
        //   },
        // ],
        // userEmail: [{ required: true, message: '请输入电子邮箱', trigger: ['blur', 'change'] }],
        userLevel: [
          {
            required: true,
            message: '请选择用户角色',
            trigger: ['blur', 'change'],
          },
        ],
        userState: [
          {
            required: true,
            message: '请选择用户状态',
            trigger: ['blur', 'change'],
          },
        ],
        // remark: [{ required: true, message: "请输入备注", trigger: ["blur", "change"] }],
        // deptId: [
        //   {
        //     required: true,
        //     message: '请选择用户所属部门',
        //     trigger: ['blur', 'change'],
        //   },
        // ],
      },
      editUserDialogVisible: false,
      editUserForm: {
        loginName: '',
        userName: '',
        loginPassword: '',
        confirmLoginPassword: '',
        userPhone: '',
        userEmail: '',
        userLevel: 1,
        deptId: '',
        userState: true,
        remark: '',
      },
      editUserFormRules: {
        loginName: [
          {
            required: true,
            message: '请输入用户名',
            trigger: ['blur', 'change'],
          },
        ],
        userName: [
          {
            required: true,
            message: '请输入真实姓名',
            trigger: ['blur', 'change'],
          },
        ],
        loginPassword: [
          {
            required: true,
            message: '请输入登陆密码',
            trigger: ['blur', 'change'],
          },
        ],
        confirmLoginPassword: [
          {
            required: true,
            message: '请再次输入密码',
            trigger: ['blur', 'change'],
          },
        ],
        // userPhone: [
        //   {
        //     required: true,
        //     message: '请输入联系电话',
        //     trigger: ['blur', 'change'],
        //   },
        // ],
        // userEmail: [
        //   {
        //     required: true,
        //     message: "请输入电子邮箱",
        //     trigger: ["blur", "change"],
        //   },
        // ],
        userLevel: [
          {
            required: true,
            message: '请选择用户角色',
            trigger: ['blur', 'change'],
          },
        ],
        userState: [
          {
            required: true,
            message: '请选择用户状态',
            trigger: ['blur', 'change'],
          },
        ],
        // remark: [{ required: true, message: "请输入备注", trigger: ["blur", "change"] }],
        // deptId: [
        //   {
        //     required: true,
        //     message: "请选择用户所属部门",
        //     trigger: ["blur", "change"],
        //   },
        // ],
      },
      roleOptions: [],
      deptOptions: [],
      userStateOptions: [
        {
          value: 1,
          label: '启用',
        },
        {
          value: 2,
          label: '禁用',
        },
      ],
      editPasswordShow: false,
    }
  },
  mounted() {
    this.getUser()
    this.getRole()
    this.getDepartment()
  },
  methods: {
    getUser() {
      getUserList(this.pageQuery).then((res) => {
        if (res.success) {
          const data = res.data.list.map((item) => {
            return {
              ...item,
              userStateCn: item.userState === 1 ? '启用' : '禁用',
            }
          })
          this.userList = data
          this.pageQuery.total = res.data.total
          this.tableLoading = false
        }
      })
    },
    getRole() {
      getRoleList().then((res) => {
        if (res.success) {
          // 转化角色列表为el-select可识别的数据结构
          this.roleOptions = res.data.list
        }
      })
    },
    getDepartment() {
      getDepartmentTree().then((res) => {
        this.deptOptions = this.transformTree(res.data, this)
      })
    },
    transformTree: (tree, _this) => {
      let arr = []
      tree.forEach((item) => {
        console.log(item)
        if (item.childTree.length !== 0) {
          item.childTree = _this.transformTree(item.childTree, _this)
        }
        arr.push({
          value: item.pkid,
          label: item.deptName,
          children: item.childTree.length > 0 ? item.childTree : null,
        })
      })
      return arr
    },
    handleEdit(row) {
      this.editPasswordShow = false
      this.editUserForm = { ...row }
      this.editUserForm.userState =
        this.editUserForm.userState === 1 ? true : false
      this.editUserDialogVisible = true
    },
    confirmAddUser() {
      this.$refs.addUserFormRef.validate((valid) => {
        if (valid) {
          const params = {
            ...this.addUserForm,
            // deptId: state.addUserForm.deptId[state.addUserForm.deptId.length - 1],
          }
          // 转化用户状态（Boolean => Number）
          params.userState = params.userState ? 1 : 2
          // Base64加密密码
          params.loginPassword = window.btoa(params.loginPassword)
          addUser(params).then((res) => {
            if (res.success) {
              this.addUserDialogVisible = false
              this.getUser()
              this.$message.success(res.data)
            } else {
              this.$message.error(res.message)
            }
          })
        }
      })
    },
    confirmEditUser() {
      this.$refs.editUserFormRef.validate((valid) => {
        if (valid) {
          const params = { ...this.editUserForm }
          // if (typeof state.editUserForm.deptId !== "string") {
          //   params.deptId = params.deptId[params.deptId.length - 1];
          // }
          if (!params.loginPassword) {
            delete params.loginPassword
          } else {
            params.loginPassword = window.btoa(params.loginPassword)
          }
          params.userState = params.userState ? 1 : 2
          delete params.loginName
          updateUser(params.pkid, params).then((res) => {
            if (res.success) {
              this.$message.success(res.data)
              this.editUserDialogVisible = false
              this.getUser()
            } else {
              this.$message.error(res.message)
            }
          })
        }
      })
    },
    removeUser(row) {
      this.$confirm(`此操作将删除用户 ${row.userName}, 是否继续?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(() => {
          deleteUser(row.pkid).then((res) => {
            if (res.success) {
              this.$message({
                type: 'success',
                message: res.data,
              })
              this.getUser()
            }
          })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除',
          })
        })
    },
    handleAddUserDialogClosed: () => {
      this.$refs.addUserFormRef.resetFields()
      this.$refs.addUserFormRef.clearValidate()
    },
    handleEditUserDialogClosed: () => {
      this.$refs.editUserFormRef.resetFields()
      this.$refs.editUserFormRef.clearValidate()
    },
  },
  watch: {
    pageQuery: {
      handler: function (newVal, oldVal) {
        if (newVal.pageIndex !== 1 && newVal.pageIndex === oldVal.pageIndex) {
          this.pageQuery.pageIndex = 1
        } else {
          this.getUser()
        }
      },
      deep: true,
    },
  },
}
</script>

<style lang="scss" scoped>
.top {
  display: flex;
  justify-content: space-between;
}
.mr-4 {
  margin-right: 10px;
}
</style>
